/*
 *所有关于Bas_RouteName类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*Bas_RouteNameService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using DGZImp.Core.BaseProvider;
using DGZImp.Core.Extensions.AutofacManager;
using DGZImp.BasProject.DomainModels;
using System.Linq;
using DGZImp.Core.Utilities;
using System.Linq.Expressions;
using DGZImp.Core.Extensions;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using DGZImp.BasProject.IRepositories;
using DGZImp.WmsProject.Dtos;
using DGZImp.Core.EFDbContext;
using DGZImp.Core.DbSqlSugar;
using System.Runtime.ConstrainedExecution;
using DGZImp.Core.Exceptions;

namespace DGZImp.BasProject.Services
{
    public partial class Bas_RouteNameService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IBas_RouteNameRepository _repository;//访问数据库
        public ISqlSugarClient Db = AutofacContainerModule.GetService<ServiceDbContext>()?.SqlSugarClient;
        [ActivatorUtilitiesConstructor]
        public Bas_RouteNameService(
            IBas_RouteNameRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        public async Task<string> copyRouteName(ReqCopyRouteName req)
        {
            if (req == null) throw new AppException("复制信息不存在");
            var RouteNameId = new Core.Utilities.IdWorker().NextId();
            // 直接插入主表
            var routeNameInfo = new Bas_RouteName
            {
                RouteCode = req.RouteCode,
                RouteName = req.RouteName,
                UseFlag = req.UseFlag,
                Version = req.Version,
                Remarks = req.Remarks,
                RouteNameId = RouteNameId
            };


            //var RouteUsage = req.Usages;
            var RouteUsage = Db.Set<Bas_RouteUsage>()
                    .LeftJoin<Bas_RouteName>((a, b) => a.RouteNameId == b.RouteNameId)
                    .Where(a => a.RouteNameId == req.RouteNameId)
                    .ToList();
            //var RouteControl = req.Controls;
            var RouteControl = Db.Set<Bas_RouteControl>()
                      .LeftJoin<Bas_RouteName>((a, b) => a.RouteNameId == b.RouteNameId)
                      .Where(a => a.RouteNameId == req.RouteNameId)
                      .ToList();
            var curControlIds = RouteControl.Select(a => a.RouteControlId).ToList();

            var deviceInfo = await Db.Set<Bas_RouteDevice>()
                .LeftJoin<Bas_RouteControl>((a, b) => a.RouteControlId == b.RouteControlId)
                .Where((a, b) => curControlIds.Contains(b.RouteControlId))
                .ToListAsync();

            var materialInfo = await Db.Set<Bas_RouteMaterial>()
                .LeftJoin<Bas_RouteControl>((a, b) => a.RouteControlId == b.RouteControlId)
                .Where((a, b) => curControlIds.Contains(b.RouteControlId))
                .ToListAsync();


            Db.Ado.BeginTran();
            try
            {

                if (RouteUsage.Count > 0)
                {

                    RouteUsage.ForEach(i => { i.RouteNameId = RouteNameId; i.RouteUsageId = 0; });
                    await Db.DoInsertAsync(RouteUsage);

                }
                if (RouteControl.Count > 0)
                {

                    foreach (var item in RouteControl)
                    {
                        var RouteControlId = new Core.Utilities.IdWorker().NextId();
                        item.RouteNameId = RouteNameId;

                        foreach (var item2 in deviceInfo)
                        {
                            if (item2.RouteControlId == item.RouteControlId)
                            {
                                item2.RouteControlId = RouteControlId;
                                item2.RouteDeviceId = 0;
                            }
                        }
                        foreach (var item2 in materialInfo)
                        {
                            if (item2.RouteControlId == item.RouteControlId)
                            {
                                item2.RouteControlId = RouteControlId;
                                item2.RouteMaterialId = 0;
                            }

                        }
                        item.RouteControlId = RouteControlId;


                    }

                    await Db.DoInsertAsync(materialInfo);
                    await Db.DoInsertAsync(RouteControl);
                    await Db.DoInsertAsync(deviceInfo);

                }
                await Db.DoInsertAsync(routeNameInfo);
                if (req.UseFlag == 1) // 如果复制的为最新，则把被复制的改为不使用
                {
                    await Db.Updateable<Bas_RouteName>()
                                  .SetColumns(a => a.UseFlag == 0)
                                  .Where(a => a.RouteNameId == req.RouteNameId).ExecuteCommandAsync();
                }
                Db.Ado.CommitTran();
                return "复制成功";
            }
            catch (Exception ex)
            {

                Db.Ado.RollbackTran();
                throw new AppException(ex.Message);
            }




        }
    }
}
